package com.fengmi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.fengmi.entity.SysPermissionEntity;
import com.fengmi.entity.SysRoleEntity;
import com.fengmi.entity.SysUserEntity;
import com.fengmi.mapper.SysUsermapper;
import com.fengmi.service.SysUserService;
import com.fengmi.util.JwtUtils;
import com.fengmi.util.RsaUtils;
import com.fengmi.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.security.PrivateKey;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUsermapper sysUsermapper;

    @Override
    public ResultVO login(SysUserEntity sysUserEntity) {
        //非空验证
        if (sysUserEntity == null) {
            return new ResultVO(false, "账号密码错误!");
        }
        //从数据库获取用户信息
        SysUserEntity userFromDB = sysUsermapper.findUserByUserName(sysUserEntity.getUserName());

        //运用bcrypt解密数据库信息 进行比较
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(sysUserEntity.getPassword(), userFromDB.getPassword())){
            return new ResultVO(false, "账号密码错误!");
        }

        //将密码制空
        userFromDB.setPassword("");

        //获取用户的角色信息
        List<SysRoleEntity> roleByUserId = sysUsermapper.findRoleByUserId(userFromDB.getUserId());
        List<String> roleStingList = roleByUserId.stream().map(role -> role.getRoleName()).collect(Collectors.toList());

        //获取角色的权限信息
        List<SysPermissionEntity> permssionByUserId = sysUsermapper.findPermssionByUserId(userFromDB.getUserId());
        List<String> permssionStringList = permssionByUserId.stream().map(permssion -> permssion.getPermDesc()).collect(Collectors.toList());

        //补全角色信息和权限信息
        userFromDB.setRoels(StrUtil.join(",",roleStingList));
        userFromDB.setPermssions(StrUtil.join(",", permssionStringList));

        //颁发jwt令牌
        try {
            //获取私钥
            PrivateKey privateKey = RsaUtils.getPrivateKey(ResourceUtils.getFile("classpath:rsa.pri").getPath());

            //获取令牌
            String token = JwtUtils.generateTokenExpireInMinutes(userFromDB, privateKey, 10);
            return new ResultVO(true, "登陆成功", token);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVO(false, "账号密码错误!");
        }
    }
}
